library(dplyr)
library(expss)
library(haven)
library(ggplot2)
library(irr)
possible.outcome = c(0,1)
outcome.labels = c('阴性','阳性')
#set.seed(11455)
n=500
n_copy = 450

get_reverse = function(e){
  if(e==1){
    return(0)
  }else{
    return(1)
  }
}
actual_state = sample(possible.outcome,n,replace=TRUE)
gold_standard = c(actual_state[1:n_copy],sample(possible.outcome,(n-n_copy),replace=TRUE))
test_assay = sample(possible.outcome,n,replace=TRUE)
test_assay2 = c(gold_standard[1:n_copy],sapply(gold_standard[(n_copy+1):n],get_reverse))
print(mcnemar.test(gold_standard,test_assay))
m_tmp = cbind(gold_standard, test_assay)
print(kappa2(m_tmp))

test_assay2 = factor(test_assay2,labels=outcome.labels)
gold_standard = factor(gold_standard,labels = outcome.labels)
test_assay = factor(test_assay,labels = outcome.labels)
actual_state = factor(actual_state,labels = outcome.labels)


df = data.frame(
  id=seq(1,n,1),
  actual_state=actual_state,
  gold_standard=gold_standard,
  test_assay=test_assay,
  test_assay2=test_assay2
)

df = apply_labels(
  df, id='id',actual_state='临床诊断',gold_standard='金标准',test_assay='无效试剂',test_assay2='模拟试剂'
)

write_sav(df,'ch6_test_assay.sav')
